
layui.define(['form', 'layedit', 'laydate','formSelects'], function (exports) {
    let $ = layui.$;
    let form = layui.form;
    let layDate = layui.laydate;


    let nameGroupIndex = $("form div.time-section").length;
    renderTime();
    zmnLayUtil.layFormVerify(form);

    //添加分组
    $('form').delegate(".addGroup","click",function () {
        //分组最多添加10个，多余10个给出提示
        let groupLegnth = $("form .time-section").length;
        if(groupLegnth>=10){
            return layer.msg("分组最多添加10个",{time: 1000});
        }
        // 组
        let current= $(this).parents('div.time-section');
        //新的组
        let newDiv = $('<div class="time-section domAdd"></div>');
        newDiv.html($('#copyDiv').html());
        // let newDiv = current.clone(false);
        //新的组中值清空，并且只保留第一个时间段
        newDiv.find("input").val('');
        let dateStrListId = ("dateStr"+new Date().getTime()*Math.random()).replace(".","");
        let timeStrListId = ("timeStrList"+new Date().getTime()*Math.random()).replace(".","");
        newDiv.find(".dateStr").attr("id",dateStrListId);
        newDiv.find(".timeStrList").attr("id",timeStrListId);
        //保留第一个时间段
        newDiv.find(".times:not(:first)").hide();
        newDiv.find("span.minusTime").hide();
        newDiv.find('.group label').text("时间段"+(++nameGroupIndex)+":")
        // let renderTimeText = newDiv.find(".dateStr");
        newDiv.insertAfter(current);
        form.render();
        layDate.render({
            elem: '#'+dateStrListId,
            range: true
        });
        layDate.render({
            elem: '#'+timeStrListId,
            type: 'time',
            range: true
        });
        checkGroupAdd();
        return false;
    });

    $('form').delegate(".minusGroup","click",function () {
        let current= $(this).parents('div.time-section');
        let configId = $(this).attr("configid");
        layer.confirm('将删除该组日期及其对应的时间段，确认删除？确认后可删除整组日期和时间段', function (index) {
           if(current.hasClass("domAdd")||!configId){
               layer.close(index);
               current.remove();
               checkGroupMinus();
           }else{
               let url = "/service/item/timeConfig/deleteGroup.action?configId="+configId
               $.post(url).then(
                   //成功回调
                   function (data) {
                       if (data.status === 200) {
                           return layer.msg("删除成功",{time: 1000},function () {
                               layer.close(index);
                               current.remove();
                               checkGroupMinus();
                           });
                       } else{
                           return layer.msg("删除失败",{time: 1000},function () {
                               layer.close(index);
                           });
                       }
                   },
                   //失败回调
                   function () {
                       layer.msg("内部错误",function () {
                           layer.close(index);
                       });
                   });
           }
        });
    });



    //添加时间段
    $('form').delegate(".addTime","click",function(){
        // 时间段
        let current= $(this).parent('div');
        let timeLegnth = current.parent("div").find(".times").length;
        if(timeLegnth>=5){
            return layer.msg("时间段最多添加5个",{time: 1000});
        }
        //新的组
        let newDiv =  $('<div class="layui-form-item times domAdd"></div>');
        newDiv.html($('#copyDiv .times').html());
        //新的时间段中值清空
        newDiv.find("input").val('');
        let timeStrListId = ("timeStrList"+new Date().getTime()*Math.random()).replace(".","");
        newDiv.find(".timeStrList").attr("id",timeStrListId);
        newDiv.insertAfter(current);
        form.render();
        // form.render();
        // let renderTimeText = newDiv.find(".timeStrList");
        layDate.render({
            elem: '#'+timeStrListId,
            type: 'time',
            range: true
        });
        checkTimeAdd(current);
        return false;
    });

    $('form').delegate(".minusTime","click",function () {
        let current= $(this).parent('div');
        let parent = current.parent('div')
        let configId = $(this).attr("configid");
        layer.confirm('确认删除时间段？', function (index) {
            if(current.hasClass("domAdd")||!configId){
                layer.close(index);
                current.remove();
                checkGroupTimeMinus(parent);
            }else{
                let url = "/service/item/timeConfig/deleteById.action?configId="+configId
                $.post(url).then(
                    //成功回调
                    function (data) {
                        if (data.status === 200) {
                            return layer.msg("删除成功",{time: 1000},function () {
                                layer.close(index);
                                current.remove();
                                checkGroupTimeMinus(parent);
                            });
                        } else{
                            return layer.msg("删除失败",{time: 1000},function () {
                                layer.close(index);
                            });
                        }
                    },
                    //失败回调
                    function () {
                        layer.msg("内部错误",function () {
                            layer.close(index);
                        });
                    });
            }
        });
    });

    // 保存按钮
    form.on('submit(zmn-form-submit)', function (obj) {
        let data = obj.field;
        let params = {};
        let timeSections = new Array();
        let timeSectionsDiv = $("form div.time-section");
        timeSectionsDiv.each((i,item)=>{
            let oneData = {};
            let groupDiv = $(item);
            let dateStr = groupDiv.find("input[name='dateStr']").val();
            let timeDivs = groupDiv.find("input[name='timeStrList']");
            let timeStrList = new Array();
            timeDivs.each((j,itemJ)=>{
                timeStrList.push($(itemJ).val());
            });
            oneData.dateStr = dateStr;
            oneData.timeStrList = timeStrList;
            timeSections.push(oneData)
        });
        params.itemId = data.itemId;
        params.configList = timeSections;


        let url = "/service/item/timeConfig/addEdit.action?itemId="+data.itemId;
        $.ajax({
            async: false,
            type: "POST", url: url,
            contentType: "application/json", dataType: "json", data: JSON.stringify(timeSections),
            beforeSend: function () {
                index = layer.load(1, {
                    shade: [0.5, '#DBDBDB']
                });
            },
            success: function (json) {
                layer.close(index);
                layer.msg(json.message,function () {
                    if(json.status==200){
                        $("#cancelBtn").click();
                        // let servCategId = $("#servCategId").val();
                        // let categOneId = $("#categOneId").val();
                        // let tariffId = $("#tariffId").val();
                        // let itemId = $("#itemId").val();
                        // parent.layui.index.refreshAndCloseTabs("/service/group/list.action?servCategId="+servCategId+"&categOneId="+categOneId+"&tariffId="+tariffId, "/service/item/detail.action?itemId="+itemId);
                    }
                });

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            },
            complete: function () {
                layer.close(index);
            }
        });

        return false;
    });
    
    $("#cancelBtn").click(function () {
        let servCategId = $("#servCategId").val();
        let categOneId = $("#categOneId").val();
        let tariffId = $("#tariffId").val();
        let itemId = $("#itemId").val();
        parent.layui.index.refreshAndCloseTabs("/service/group/list.action?servCategId="+servCategId+"&categOneId="+categOneId+"&tariffId="+tariffId, "/service/item/detail.action?itemId="+itemId);
    });



    //渲染时间空间，同时检查渲染出来的dom是否移除“删除”图标
    function renderTime(){
        let groupDiv= $("form div.time-section");
        if(groupDiv.length==1){
            let configid = groupDiv.find(".group span.minusGroup").attr("configid");
            if(!configid){
                groupDiv.find(".minusGroup").hide();
                groupDiv.find(".minusTime").hide();
            }else{
                let timesDiv = groupDiv.find("div.times");
                timesDiv.find(".minusTime").hide();
                if(timesDiv.length>1){
                    timesDiv.find(".minusTime").show();
                }
            }
        }

        $('form .dateStr').each(function(){
            let eId = $(this).attr("id");
            layDate.render({
                elem: '#'+eId,
                range: true
            });
        });
        $('form .timeStrList').each(function(){
            let eId = $(this).attr("id");
            layDate.render({
                elem: '#'+eId,
                type: 'time',
                range: true
            });
        });
    }

    //删除分组的时候检查是否只存在一个group，存在一个的情况下，去掉删除图标
    function checkGroupMinus(){
        let allGroup = $("form div.time-section");
        if(allGroup.length==0){
            location.reload();
        }
        if(allGroup.length>1){
            return;
        }else{
            allGroup.find("span.minusGroup").hide();
        }

    }

    //添加分组的时候检查如果存在多个分组，那么删除图标显示
    function checkGroupAdd(){
        let allGroup = $("form div.time-section");
        if(allGroup.length>1){
            $("form .time-section").find(".minusGroup").show();
        }
    }

    //添加时间段的时候检查如果存在多个时间段，存在那么删除图标显示
    function checkTimeAdd(current){
        let sublings = current.parent("div").find(".times");
        if(sublings.length>1){
            sublings.find("span.minusTime").show();
        }else{
            sublings.find("span.minusTime").hide();
        }
    }

    //检查当前的group中是否只存在一个子节点，如果只存在一个，那么去掉删除图标
    function checkGroupTimeMinus(current){
        let sublings = current.find(".times");
        if(sublings.length>1){
            return;
        }else{
            sublings.find("span.minusTime").hide();
        }
    }



    //对外暴露的接口
    exports('serv_service_item_config_detail', {});
});